/*
 *  Copyright (C) 2009 Dominik Psenner
 * 
 *   This file is part of WebDAV4JD.
 *
 *  WebDAV4JD is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  WebDAV4JD is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with project-blog.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package com.lab9.webdav4jd.api.impl.datasource;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.lab9.webdav4jd.api.DataSource;
import com.lab9.webdav4jd.api.exceptions.UnsupportedException;
import com.lab9.webdav4jd.api.properties.ResponseCode;
import com.lab9.webdav4jd.core.HttpHeader;
import com.lab9.webdav4jd.core.HttpRequest;
import com.lab9.webdav4jd.core.HttpResponse;

/**
 * @author dominik
 * 
 */
public class GoogleAppengine implements DataSource {
	private final URLFetchService serv;
	
	private final String url;
	
	public GoogleAppengine(final String url) {
		serv = URLFetchServiceFactory.getURLFetchService();
		this.url = url;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final String getURL() {
		return url;
	}
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public final HttpResponse fetch(final HttpRequest request) throws IOException {
		final HTTPResponse response = serv.fetch(request.getURL());
		final List<HttpHeader> headers = new LinkedList<HttpHeader>();
		for (final HTTPHeader h : response.getHeaders()) {
			headers.add(new HttpHeader(h.getName(), h.getValue()));
		}
		try {
			return new HttpResponse(ResponseCode.get(response.getResponseCode()), headers, response.getContent());
		}
		catch (final UnsupportedException e) {
			throw new IOException(e);
		}
	}
}
